<template>
  <div class="page-wapper">
    <!-- 任务视图 -->
    <div class="container" :class="{ full_screen: isFullScreen }">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">版本：</div>
            <el-select
              v-model="filterData.releaseId"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.releaseIdSelectList"
                :key="item.id"
                :label="item.releaseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>

          <div class="filter_item">
            <div class="label">任务优先级：</div>
            <el-select
              v-model="filterData.taskPriority"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.taskPrioritySelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div class="filter_item">
            <div class="label">任务状态：</div>
            <el-select
              v-model="filterData.taskStatus"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.taskStatusSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <!-- 标签筛选列 -->
        <el-popover placement="bottom-start" trigger="click" width="600px">
          <div style="display: flex; flex-wrap: wrap">
            <div style="width: 200px">
              <el-checkbox
                v-model="columnsAll.visible"
                @change="tagCheckedChange(columnsAll)"
                >全选
              </el-checkbox>
            </div>
            <template v-for="(item, i) in columns">
              <div v-if="item.title" :key="i" style="width: 200px">
                <el-checkbox
                  v-model="item.visible"
                  :disabled="disabledCancleColumns.includes(item.title)"
                  @change="tagCheckedChange(item)"
                  >{{ item.title }}
                </el-checkbox>
              </div>
            </template>
          </div>

          <template #reference>
            <el-button type="primary" size="mini">筛选列</el-button>
          </template>
        </el-popover>
        <div>
          <el-button size="mini" type="primary" @click="createTableData">
            新建
          </el-button>
          <el-button size="mini" type="danger" @click="batchdelete">
            删除
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-if="tableData.length"
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :span-method="mergeRowMethod"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          show-header-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
        >
          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>

          <TableColum :colums="tableColum"> </TableColum>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 编辑弹框 -->
    <!-- <TaskFormDialog
      ref="taskFormDialogRef"
      :prepareData="prepareData"
      @refresh="getTableData"
    /> -->
  </div>
</template>

<script>
import {
  ref,
  toRefs,
  reactive,
  onMounted,
  nextTick,
  getCurrentInstance,
  onActivated,
} from "vue";
import TaskFormDialog from "./components/TaskFormDialog.vue";
import TableColum from "../../components/TabelTemplate/TableColum.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const initFilterData = () => {
  return {
    moduleIds: null,
    taskStatus: null,
    releaseId: null,
    taskPriority: null,
  };
};

const initTableColum = () => {
  return {
    // moduleNamesArr: {
    //   title: "所属模块",
    //   props: {  sortable: false },
    //   slotContent: 'moduleNamesArr'
    // },
    taskTitle: {
      title: "任务标题",
      props: { sortable: false },
    },
    taskStatusLabel: {
      title: "任务状态",
      props: { sortable: false },
    },
    taskRemark: {
      title: "任务备注",
      props: { sortable: false },
    },
    taskPriorityLabel: {
      title: "任务优先级",
      props: { sortable: false },
    },
    demandUserName: {
      title: "需求负责人",
      props: { sortable: false },
    },
    demandCompleteTime: {
      title: "需求完成时间",
      props: { sortable: false },
    },
    demandStatus: {
      title: "需求状态",
      props: { sortable: false },
    },
    demandAuditTime: {
      title: "需求评审时间",
      props: { sortable: false },
    },
    workUserName: {
      title: "开发负责人",
      props: { sortable: false },
    },
    workPlanCompleteTime: {
      title: "开发计划完成时间",
      props: { sortable: false },
    },
    workProgress: {
      title: "开发完成程度",
      props: { sortable: false },
    },
    workPlanDays: {
      title: "开发预估工作量（天）",
      props: { sortable: false },
    },
    workRemark: {
      title: "开发备注",
      props: { sortable: false },
    },
    workActualCompleteTime: {
      title: "开发实际完成时间",
      props: { sortable: false },
    },
    workActualDays: {
      title: "开发实际投入时间（天）",
      props: { sortable: false },
    },
    asNeedTest: {
      title: "是否需要测试",
      props: { sortable: false },
    },
    asPassDevTest: {
      title: "是否通过冒烟测试",
      props: { sortable: false },
    },
    testDesc: {
      title: "测试说明",
      props: { sortable: false },
    },
    testUserName: {
      title: "测试负责人",
      props: { sortable: false },
    },
    testStartTime: {
      title: "测试开始时间",
      props: { sortable: false },
    },
    testOneProgress: {
      title: "测试一轮进度",
      props: { sortable: false },
    },
    testTwoProgress: {
      title: "测试二轮进度",
      props: { sortable: false },
    },
    testBackProgress: {
      title: "测试回归进度",
      props: { sortable: false },
    },
    testRemark: {
      title: "测试备注",
      props: { sortable: false },
    },
  };
};

export default {
  name: "TaskManage",
  components: { TaskFormDialog, TableColum },
  setup() {
    const { proxy } = getCurrentInstance();
    console.log("proxy =>", proxy);
    const $api = proxy.$api;

    const taskFormDialogRef = ref(null);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});

    // 预加载数据
    const prepareData = reactive({
      taskStatusSelectList: [],
      releaseIdSelectList: [],
      taskPrioritySelectList: [],
    });

    const columnsAll = reactive({
      visible: true,
      title: "全选",
    });
    // 标签筛选列
    const columns = ref([]);
    // 列表标签筛选需要禁用筛选的选项
    const disabledCancleColumns = ref(["序号", "任务标题", "任务状态", "操作"]);

    const xTable = ref(null);
    const tableData = ref([]);
    const tableLoading = ref(false);
    const searchBtnLoading = ref(false);
    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    const tableColumData = reactive({
      tableColum: {},
    });

    // setTimeout(() => {
    //   nextTick(() => {
    //     // 刷新布局
    //     xTable.value.refreshColumn();
    //   });
    // }, 500);

    const isFullScreen = ref(false);
    const toggleFullScreen = () => {
      isFullScreen.value = !isFullScreen.value;
    };

    const handleRead = (index) => {};
    const handleDel = (index) => {};
    const handleRestore = (index) => {};

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    const columsObj = {};

    // 获取列表数据
    const getTableData = () => {
      tableLoading.value = true;
      $api.task
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableLoading.value = false;
          console.log("tableData => res", res);
          const data = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              moduleNamesArr: item.moduleNames
                .split("|")
                .filter((item) => item),
              moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
            };
          });
          // 生成动态列
          // 找出最大列数
          let columsCount = 1;
          data.forEach((item) => {
            if (item.moduleIdsArr.length > columsCount) {
              columsCount = item.moduleIdsArr.length;
            }
          });
          console.log("找出最大列数 => columsCount", columsCount);
          data.forEach((item) => {
            for (let i = 0; i < columsCount; i++) {
              let moduleId = null;
              let moduleName = null;
              if (item.moduleIdsArr.length > i) {
                moduleId = item.moduleIdsArr[i];
              }
              if (item.moduleNamesArr.length > i) {
                moduleName = item.moduleNamesArr[i];
              }
              item["moduleId" + (i + 1)] = moduleId;
              item["moduleName" + (i + 1)] = moduleName;
              columsObj["moduleName" + (i + 1)] = {
                title: `模块${i + 1}`,
                props: { sortable: false },
              };
            }
          });

          tableColumData.tableColum = {
            ...columsObj,
            ...initTableColum(),
          };

          tableData.value = data;

          // nextTick(() => {
          //   tableData.value = data;
          // });

          console.log("tableColum ===>", tableColumData.tableColum);
          console.log("tableData ===>", tableData.value);

          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("tableData error: ", err);
        });
    };

    // 新建
    const createTableData = () => {
      nextTick(() => {
        taskFormDialogRef.value.open();
      });
    };

    // 编辑内容
    const editTableDataMethod = (row) => {
      nextTick(() => {
        taskFormDialogRef.value.open(row);
      });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.taskTitle.length > 10
            ? row.taskTitle.slice(0, 10) + "..."
            : row.taskTitle
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 批量删除
    const batchdelete = () => {
      if (!tableData.value.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableLoading.value = true;
      $api.task
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 获取任务预加载数据
    const getPreparedData = () => {
      $api.task
        .preparedData()
        .then((res) => {
          Object.keys(prepareData).forEach((key) => {
            prepareData[key] = res.data[key];
          });
        })
        .catch((err) => {
          console.error("getPreparedData error: ", err);
        })
        .finally(() => {
          // formDialogLoading.value = false;
        });
    };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        columns.value.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            disabledCancleColumns.value.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      columnsAll.visible = columns.value.every((item) => item.visible);
      // 刷新布局
      xTable.value.refreshColumn();
    };

    // 查询已设置为标签的版本列表
    const getRoofList = () => {
      $api.release
        .roofList()
        .then((res) => {
          prepareData.releaseIdSelectList = res.data.list;
        })
        .catch((err) => {
          console.error("getRoofList error: ", err);
        })
        .finally(() => {
          // formDialogLoading.value = false;
        });
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 通用行合并函数（将相同多列数据合并为一行）
    const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
      const fields = Object.keys(columsObj);
      const cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    };

    // 初始化
    getPreparedData();
    handleSearch();

    onActivated(() => {
      getRoofList();
    });

    return {
      xTable,
      tableData,
      tableLoading,
      handleRead,
      handleDel,
      handleRestore,
      isFullScreen,
      toggleFullScreen,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      prepareData,
      createTableData,
      editTableDataMethod,
      deleteTableDataMethod,
      tagCheckedChange,
      columns,
      columnsAll,
      disabledCancleColumns,
      getTableData,
      taskFormDialogRef,
      pagenationData,
      handleSizeChange,
      handleCurrentChange,
      batchdelete,
      mergeRowMethod,
      ...toRefs(tableColumData),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
